<script setup xmlns="http://www.w3.org/1999/html">
import {nextTick, onBeforeUnmount, onMounted, onUnmounted, ref, watch} from "vue";
import Say from "@/components/say.vue";
import {deleteAiTalk, getAITalkService, saveAITalks} from "@/api/AITalk.js";
import {useTokenStore} from "@/stores/token.js";
import {ElMessage} from "element-plus";
import {getUserInfoService} from "@/api/user.js";
import {useRouter} from "vue-router";
import {useDefaultAvatarStore} from "@/stores/defaultAvatar.js";

const route = useRouter()
const tokenStore = useTokenStore()
const message = ref('')
const title = ref('')
const scrollArea = ref(null)

//用户头像
const userAvatar =ref()
const getUserInfo = async ()=>{
  let result = await getUserInfoService();
  //获取头像地址
  userAvatar.value = result.data.userPic
}
getUserInfo();
const defaultAvatarStore = useDefaultAvatarStore();
//默认头像
const defaultPic = ref(defaultAvatarStore.defaultAvatar)

const says = ref([
  {
    role: "assistant",
    content: '你好，我是校林官方AI大模型，我叫小林，我具备大量的二手交易知识和信息，可以帮助你解答关于商品类型、价格评估、交易流程、市场趋势等方面的问题。如果你有任何关于二手交易的疑问，我会尽力提供有用的信息和建议。请随时提问！'
  }
])

const loadingTexts = '生成中...';

const sendMessage = async () => {
  if (tokenStore.token === '') {
    ElMessage.error('请先登录')
    return;
  }
  if (message.value === '') {
    return;
  }
  let userContent = {"role": "user", "content": message.value};
  says.value.push(userContent);
  toScrollBottom();
  await saveAITalks(says.value.slice(1,says.value.length));
  //加载中的提示文本
  says.value.push({"role": "assistant", "content": loadingTexts});
  toScrollBottom();
  let sayLength = says.value.length;
  message.value = '';
  const eventSource = getAITalkService();
  eventSource.onopen = function (event) {
    console.log('sse连接成功');
  };

  eventSource.onmessage = function (event) {
    let result = JSON.parse(event.data);
    // 解析接收到的数据
    if (result.content === '[DONE]') {
      console.log('sse连接结束')
      eventSource.close();
    } else {
      //处理数据
      if (sayLength === says.value.length) {
        //删除加载中的提示文本
        says.value.pop();
        says.value.push(result)
      } else {
        says.value[sayLength].content = result.content;
      }
      toScrollBottom();
    }

  };

  eventSource.onerror = function (event) {
    if (event.readyState === EventSource.CLOSED) {
      // 处理连接关闭的情况，例如显示错误信息或重新连接
      console.log('sse关闭');
    } else {
      // 处理其他错误，例如网络问题
      console.error('EventSource 错误:', event);
    }
  };
}

//监听回车事件
const sendMessageByEnter = (event) => {
  event.stopPropagation();
  if (event.ctrlKey && event.key === 'Enter'){
    event.preventDefault();
    message.value += '\n';
  }
  if (event.key === 'Enter' && !event.ctrlKey){
    event.preventDefault();
    sendMessage();
  }
}
document.addEventListener("keydown", sendMessageByEnter);

const handleBeforeUnmount = (event) => {
  event.preventDefault();
  deleteAiTalk();
  return true;
}
window.addEventListener('beforeunload', handleBeforeUnmount);

onMounted(()=>{
  title.value = route.currentRoute.value.meta.title;
  document.title = title.value;

  loadAI();
})

const toScrollBottom = () =>{
  if (scrollArea.value){
    nextTick(()=>{
      scrollArea.value.scrollTop = scrollArea.value.scrollHeight;
    })
  }
}

onBeforeUnmount(()=>{
  document.removeEventListener("keydown", sendMessageByEnter);
  window.removeEventListener('beforeunload', handleBeforeUnmount);
})
const flag = ref(0)
const showContent = ref(false)
const loadAI = ()=>{
    for (let i = 1; i < 101; i++){
      setTimeout(()=>{
        flag.value = i;
        if (i === 100){
          showContent.value = true
        }
      },10)
    }
}
</script>

<template>
  <div v-if="showContent" class="ai-container">
    <div class="ai-header">
      <span>校林AI助手</span>
    </div>
    <div class="ai-main">
      <div ref="scrollArea" class="ai-content">
        <div style="height: 100vh-100px;">
          <say v-for="(item,index) in says" :key="index" :role="item.role" :content="item.content" :avatar="userAvatar === null ? defaultPic : userAvatar"/>
        </div>
      </div>
      <div class="ai-message">
        <textarea class="message-input" v-model="message" placeholder="在这里输入问题，Enter发送  Ctrl+Enter换行"></textarea>
        <div class="buttons">
<!--          <el-button class="ai-message-button" type="danger"  @click="sendMessage">返回</el-button>-->
          <el-button class="ai-message-button" type="primary" @click="sendMessage">发送</el-button>
        </div>
      </div>
    </div>
  </div>
  <div v-else class="ai-container">
    <div class="ai-header">
      <span>校林AI助手</span>
    </div>
    <div class="progress" style="display: flex;flex-direction: column;justify-content: center;align-items: center;height: 60%;">
      <el-progress
          :text-inside="true"
          :stroke-width="26"
          :percentage="flag"
          style="width: 80%;"
      />
      <p style="color: rgba(0,0,0,0.5)">模型加载中...</p>
    </div>
  </div>
</template>

<style scoped>
.ai-container {
  height: 100vh;
  width: 100%;
  overflow-y: hidden;
}

.ai-header {
  background-color: #fcfcfc;
  height: 8vh;
  border-bottom: 1px solid #d7d7d7;

  span {
    color: black;
    font-size: 20px;
    margin-left: 30px;
    font-weight: bold;
    margin-top: 10px;
    margin-bottom: 10px;
    display: inline-block;
    line-height: 40px;
  }
}

.ai-main {
  background-color: #ffffff;
  width: 100%;
  height: 92vh;

  .ai-content {
    height: 84%;
    background-color: #ffffff;
    border-bottom: 1px solid #d7d7d7;
    overflow-y: auto;
  }

  .ai-message {
    height: 16%;
    background-color: white;


    .ai-message-button {
      height: 30%;
      width: 10%;
      margin-right: 20px;
    }
  }
}
.buttons{
  display: flex;
  justify-content: flex-end;
}
.message-input{
  width: 97%;
  border: none;
  height: 46%;
  resize: none;
  color: black;
  font-size: 18px;
  padding: 10px;
  &:focus{
    outline: none;
    box-shadow: none;
  }
}
</style>